package com.ychp.user.service.impl;

import com.google.common.base.Throwables;
import com.ychp.common.encryption.Encryption;
import com.ychp.common.model.Response;
import com.ychp.user.dao.UserDao;
import com.ychp.user.dao.redis.UserRedisDao;
import com.ychp.user.model.User;
import com.ychp.user.service.UserWriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Desc:
 * Author: <a href="ychp@terminus.io">应程鹏</a>
 * Date: 16/11/7
 */
@Slf4j
@Service
public class UserWriteServiceImpl implements UserWriteService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRedisDao userRedisDao;

    public Response<User> autoLogin(String token) {

        return null;
    }

    public Response<Boolean> create(User user) {
        try{
            if(user == null){
                return Response.fail("user.empty");
            }
            if(user.getLoginName() == null && Objects.equals(user.getLoginName().trim(), "")){
                return Response.fail("user.loginName.empty");
            }
            if(user.getPlainPassword() == null && Objects.equals(user.getPlainPassword().trim(), "")){
                return Response.fail("user.password.empty");
            }

            user.setSalt(Encryption.getSalt());
            user.setPassword(Encryption.Encrypt3DES(user.getPlainPassword(), user.getSalt()));
            userDao.insert(user);
            return Response.ok(true);
        } catch (Exception e){
            log.error("create user fail, user={}, case:{}", user, Throwables.getStackTraceAsString(e));
            return Response.fail("user.create.fail");
        }
    }
}
